import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import mime from 'mime'

export async function GET(request: Request, { params }: { params: {  filename: string } }) {
  try {
    const {  filename } = params
    
    // 安全检查：防止路径遍历攻击
    if (filename.includes('..') || filename.includes('/')) {
      return NextResponse.json(
        { error: 'Invalid filename' },
        { status: 400 }
      )
    }
    
    const filePath = path.join(process.cwd(), 'uploads', filename)
    
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return NextResponse.json(
        { error: 'File not found' },
        { status: 404 }
      )
    }
    
    // 读取文件内容
    const fileBuffer = fs.readFileSync(filePath)
    
    // 获取文件MIME类型
    const contentType = mime.getType(filename) || 'application/octet-stream'
    
    // 设置响应头
    const headers = new Headers()
    headers.set('Content-Type', contentType)
    headers.set('Content-Disposition', `inline; filename="${filename}"`)
    
    return new NextResponse(fileBuffer, {
      status: 200,
      headers
    })
  } catch (error) {
    console.error('文件下载失败:', error)
    return NextResponse.json(
      { error: 'Failed to download file' },
      { status: 500 }
    )
  }
}